/**
 * Created by luqidong on 2017/6/8.
 */
import TDbridge from './bridge/index';
import {getMytoken, authorizationcodeR, authorizationR} from '../service/common';
export const addCommas = (val)=> {
    return val && val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
export function isEmptyObject(obj) {
    return Object.keys(obj).length === 0;
}

export function isjson(obj) {
    return typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
}

export function isphone(value) {
    var reg = /^1[0-9]{10}$/;
    return reg.test(value);
}

/**
 * 加
 * @param num1
 * @param num2
 * @returns {number}
 */
export function numAdd(num1, num2) {
    var baseNum, baseNum1, baseNum2;
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    return (num1 * baseNum + num2 * baseNum) / baseNum;
};
/**减法
 * @return {number}
 */
export function numSub(num1, num2) {
    var baseNum, baseNum1, baseNum2;
    var precision;// 精度
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
    return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
};
/**
 * 除以
 * @return {number}
 */
export function Div(a, b) {
    var n1 = 0,
        n2 = 0;
    var baseNum3, baseNum4;
    try {
        n1 += a.toString().split(".")[1].length;
    } catch (e) {
    }
    try {
        n2 += b.toString().split(".")[1].length;
    } catch (e) {
    }
    return (a * Math.pow(10, n1)) / (b * Math.pow(10, n2)) / Math.pow(10, n1 - n2);
}


/**
 * 乘以
 * @return {number}
 */
export function Mul(a, b) {
    var n1 = 0,
        n2 = 0;
    try {
        n1 += a.toString().split(".")[1].length;
    } catch (e) {
    }
    try {
        n2 += b.toString().split(".")[1].length;
    } catch (e) {
    }
    return (a * Math.pow(10, n1)) * (b * Math.pow(10, n2)) / Math.pow(10, n1 + n2);
}

export function openIfram(url) {
    // 第一部分
    var dom, doc, where, iframe = document.createElement('iframe');
    iframe.src = "javascript:false";
    iframe.title = "";
    iframe.role = "presentation";
    (iframe.frameElement || iframe).style.cssText = "width: 0; height: 0; border: 0";
    where = document.getElementsByTagName('script');
    where = where[where.length - 1];
    where.parentNode.insertBefore(iframe, where);

    // 第二部分
    try {
        doc = iframe.contentWindow.document;
    } catch (e) {
        // IE下如果主页面修改过document.domain，那么访问用js创建的匿名iframe会发生跨域问题，必须通过js伪协议修改iframe内部的domain
        dom = document.domain;
        iframe.src = "javascript:var d=document.open();d.domain='" + dom + "';void(0);";
        doc = iframe.contentWindow.document;
    }
    doc.open()._l = function () {
        var js = this.createElement("script");
        if(dom) this.domain = dom;
        js.id = "js-iframe-async";
        js.src = url;
        this.body.appendChild(js);
    };
    doc.write('<body onload="document._l();">');
    doc.close();
}
export function isiOS(u) {
    //noinspection JSDuplicatedDeclaration
    var u = u || window.navigator.userAgent;
    return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
}

export function toDecimal(x) {
    var f = parseFloat(x);
    if(isNaN(f)) {
        return;
    }
    f = Math.round(x * 100) / 100;
    return f;
}
export function toDecimal2(x) {
    var f = parseFloat(x);
    if(isNaN(f)) {
        return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if(rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}


export function postcall(url, params, target) {
    var tempform = document.createElement("form");
    tempform.action = url;
    tempform.method = "post";
    tempform.style.display = "none";
    if(target) {
        tempform.target = target;
    }

    for (var x in params) {
        var opt = document.createElement("input");
        opt.name = x;
        opt.value = params[x];
        tempform.appendChild(opt);
    }

    var opt = document.createElement("input");
    opt.type = "submit";
    tempform.appendChild(opt);
    document.body.appendChild(tempform);
    tempform.submit();
    document.body.removeChild(tempform);
}
export function parseDom(arg) {

    var objE = document.createElement("div");
    objE.style.display = 'none';

    objE.innerHTML = arg;

    return objE;

}
export function isWeixinBrowser() {
    return /micromessenger/.test(navigator.userAgent.toLowerCase())
}
export function addEvent(obj, type, fn) {
    if(obj.attachEvent) {
        obj['e' + type + fn] = fn;
        obj[type + fn] = function () {
            obj['e' + type + fn](window.event);
        };
        obj.attachEvent('on' + type, obj[type + fn]);
    } else
        obj.addEventListener(type, fn, false);
}
export function removeEvent(obj, type, fn) {
    if(obj.detachEvent) {
        obj.detachEvent('on' + type, obj[type + fn]);
        obj[type + fn] = null;
    } else
        obj.removeEventListener(type, fn, false);
}

export function setTitle(value) {
    //原生修改title 顺便改document的title 哎 坑比
    try {
        TDbridge.appPlugin.startAppPlugin({
            'type': 14,
            'message': `${value}`
        });
    }
    catch (e) {
        document.title = value;
    }
}

export function h5tonative(title, url, fn) {
    const jumphhdata = {
        "title": `${title}`,
        "pageType": "1",
        "url": url.indexOf('http') > -1 ? url : `${location.origin}/#${url}`,
        "jumpType": "2"
    };
    try {
        TDbridge.skipApp.startSkipApp(jumphhdata);// 跳转
    }
    catch (e) {
        fn && fn();
    }
}
export function h5toh5htmlclose(title, payCode, html, fn) {
    const jumphhdata = {
        "title": `${title}`,
        "pageType": "2006",
        "jumpType": "2",
        params: {payCode, html}
    };
    try {
        TDbridge.skipApp.startSkipApp(jumphhdata);// 跳转
    }
    catch (e) {
        fn && fn();
    }
}

export function h5tonativeclose(title, url, fn) {
    const jumphhdata = {
        "title": `${title}`,
        "pageType": "2006",
        "url": url.indexOf('http') > -1 ? url : `${location.origin}/#${url}`,
        "jumpType": "2"
    };
    try {
        TDbridge.skipApp.startSkipApp(jumphhdata);// 跳转
    }
    catch (e) {
        fn && fn();
    }
}
export function nativetonative(pageType) {
    if(pageType === 'home') {
        try {
            TDbridge.appPlugin.startAppPlugin({'type': 8});
            TDbridge.appPlugin.startAppPlugin({'type': 21});
            return;
        }
        catch (e) {

        }

    }
    let senddata = {
        pageType,
        jumpType: 1
    };

    try {
        TDbridge.skipApp.startSkipApp(senddata);
    }
    catch (e) {

    }
}
export function createTempIfram(url) {
    var i = document.createElement('iframe');
    i.src = url;
    i.style.display = 'none';
    i.onload = function () {
        setTimeout(function () {
            i.remove()
        }, 9)
    };
    document.body.appendChild(i)
}

// 计算加载时间
export function getPerformanceTiming() {
    var performance = window.performance;

    if(!performance) {
        // 当前浏览器不支持
        console.log('你的浏览器不支持 performance 接口');
        return;
    }

    var t = performance.timing;
    var times = {};

    //【重要】页面加载完成的时间
    //【原因】这几乎代表了用户等待页面可用的时间
    times.loadPage = t.domLoading - t.navigationStart;

    //【重要】解析 DOM 树结构的时间
    //【原因】反省下你的 DOM 树嵌套是不是太多了！
    times.domReady = t.domLoading - t.fetchStart;

    //【重要】重定向的时间
    //【原因】拒绝重定向！比如，http://example.com/ 就不该写成 http://example.com
    times.redirect = t.redirectEnd - t.redirectStart;

    //【重要】DNS 查询时间
    //【原因】DNS 预加载做了么？页面内是不是使用了太多不同的域名导致域名查询的时间太长？
    // 可使用 HTML5 Prefetch 预查询 DNS ，见：[HTML5 prefetch](http://segmentfault.com/a/1190000000633364)
    times.lookupDomain = t.domainLookupEnd - t.domainLookupStart;

    //【重要】读取页面第一个字节的时间
    //【原因】这可以理解为用户拿到你的资源占用的时间，加异地机房了么，加CDN 处理了么？加带宽了么？加 CPU 运算速度了么？
    // TTFB 即 Time To First Byte 的意思
    // 维基百科：https://en.wikipedia.org/wiki/Time_To_First_Byte
    times.ttfb = t.responseStart - t.navigationStart;

    //【重要】内容加载完成的时间
    //【原因】页面内容经过 gzip 压缩了么，静态资源 css/js 等压缩了么？
    times.request = t.responseEnd - t.requestStart;

    //【重要】执行 onload 回调函数的时间
    //【原因】是否太多不必要的操作都放到 onload 回调函数里执行了，考虑过延迟加载、按需加载的策略么？
    times.loadEvent = t.loadEventEnd - t.loadEventStart;

    // DNS 缓存时间
    times.appcache = t.domainLookupStart - t.fetchStart;

    // 卸载页面的时间
    times.unloadEvent = t.unloadEventEnd - t.unloadEventStart;

    // TCP 建立连接完成握手的时间
    times.connect = t.connectEnd - t.connectStart;

    return times;
}

export function closeThisPage() {
    TDbridge.appPlugin.startAppPlugin({'type': 8});
}

export const delay = timeout => {
    return new Promise(resolve => {
        setTimeout(resolve, timeout);
    });
};

export const setDocumentTitle = function (title) {
    document.title = title;
    let ua = navigator.userAgent;
    setTitle(title);
    if(/\bMicroMessenger\/([\d.]+)/.test(ua) && /ip(hone|od|ad)/i.test(ua)) {
        var i = document.createElement('iframe');
        i.src = '/favicon.ico';
        i.style.display = 'none';
        i.onload = function () {
            setTimeout(function () {
                i.remove()
            }, 9)
        };
        document.body.appendChild(i)
    }
};

export function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if(r != null) return unescape(r[2]);
    return null; //返回参数值
}
export function getHash(url) {
    return decodeURIComponent(url ? url.substring(url.indexOf('#') + 1) : window.location.hash.substr(1));
}

export const isWeixin = ()=> { //判断是否是微信
    var ua = navigator.userAgent.toLowerCase();
    return ua.match(/MicroMessenger/i) == "micromessenger";
};


const authorization = async()=> {
    if(!isWeixin()) {
        return;
    }
    const {token}=await getMytoken(true);
    if(!token) {
        const url = location.href;
        const code = getUrlParam('code');

        if(code) {
            const {data} = await authorizationcodeR(code);
            if(data && data.code === 0) {
                const {Guid}=data.data;
                store2('userInfo', {...data.data, token: Guid});
                return;
            }
        }
        const {data}=await authorizationR(encodeURIComponent(url));
        if(data && data.code === 0) {
            location.href = data.data;
        }
    }
}
